<?php
// +----------------------------------------------------------------------
// | @description 微信调用的类
// +----------------------------------------------------------------------
// | @version  
// +----------------------------------------------------------------------
// | Author:xyd
// +----------------------------------------------------------------------
namespace Common\wx;


class wxOuth
{
    // 微信的配置文件
    private $weconfig;
    // 微信的接口对象
    private $wechatObj;
    // 微信返回的json
    public $wxjson;
    
    // 默认微信配置文件
    const WEIXIN_FILE = 'wxconfig.php';

    /**
     * 设置微信默认的配置文件
     */
    public function getWeConfig ()
    {
        if (! isset($this->weconfig))
        {
            $this->weconfig = require (CONF_PATH . self::WEIXIN_FILE);
            $this->wechatObj = new Wechat($this->weconfig);
        }
    }

    /**
     * 静默获取用户的openId
     * 
     * @param string $options            
     * @return void|unknown
     */
    public function getOpenidByBaseOauth ($options = NULL, $type = 'openId')
    {
        if ($options != NULL)
        {
            $this->weconfig = $options;
        }
        $this->getWeConfig();
        $result = $this->wechatObj->getOauthAccessToken();
        if (! $result)
        {
            $current_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            $current_url = str_replace('code=', 'code0=', $current_url);
            redirect($this->wechatObj->getOauthRedirect($current_url, 1, 'snsapi_base'));
            R('Public/err');
            return;
        }
        if ($type == 'AccessToken')
        {
            return $result;
        }
        $openid = $result['openid'];
        return $openid;
    }

    
    public function getWxUserOpenIdAndUnioid(){
        $this->getWeConfig();
        $result = $this->wechatObj->getOauthAccessToken();
        
        if (! $result)
        {
            $current_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            $current_url = str_replace('code=', 'code0=', $current_url);
            redirect($this->wechatObj->getOauthRedirect($current_url, 1, 'snsapi_base'));
            R('Public/err');
            return;
        }
        $userinfo2 = $this->wechatObj->getUserInfo($result['openid']);
        //获得openID
        $retrunArr['headimgurl']=$userinfo2['headimgurl'];
        $retrunArr['nickname']=$userinfo2['nickname'];
        $retrunArr['openId']=$userinfo2['openid'];
        $retrunArr['unionid']=$userinfo2['unionid'];
        $retrunArr['authMessage']=json_encode($userinfo2);
        // 添加是那个公众号的用户的openId
        return $retrunArr;
    }
    /**
     * 授权获取用户的信息
     */
    public function getWeixinUserinfoByUserOauth(){
        $this->getWeConfig();
        $isOauth = $_GET['isOauth'];
       
        if (isset($isOauth) && $isOauth == '1'){ //说明需要弹出授权框
            // 获得用户AccessToken
            $result = $this->wechatObj->getOauthAccessToken();
            $userinfo = $this->wechatObj->getOauthUserinfo($result['access_token'], $result['openid']);
            $this->wxjson=json_encode($userinfo);
            
            if (!$result){
                $current_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                $current_url = str_replace('code=', 'code0=', $current_url);
                redirect($this->wechatObj->getOauthRedirect($current_url, 1, 'snsapi_base'));
                exit();
            }
            // 获得用户关注的用户信息
            $userinfo2 = $this->wechatObj->getUserInfo($result['openid']);
        }else{
            // 静默获取openid
            $result = $this->getOpenidByBaseOauth(NULL, 'AccessToken');
            dump($result);
            // 检验数据库是否存在此用户
            // $userRes = M('user')->where(array('openid' => $result['openid']))->field('updatetime')->find();
            if ($userRes != NULL){
                // 判断是否用户信息
                $updateinfo['nickname'] = $result['nickname'];
            }else{
                $current_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" . "&isOauth=1";
                $current_url = str_replace('code=', 'code0=', $current_url);
                redirect($this->wechatObj->getOauthRedirect($current_url, 1, 'snsapi_userinfo'));
            }
        }
    }
    /**
     * 授权获取用户的信息
     */
    public function getWeixinUserinfoByUserOauth2()
    {
        $this->getWeConfig();
        $isOauth = $_GET['isOauth'];
       
        if (isset($isOauth) && $isOauth == '1')
        { //说明需要弹出授权框
            // 获得用户AccessToken
            $result = $this->wechatObj->getOauthAccessToken();
            $userinfo = $this->wechatObj->getOauthUserinfo($result['access_token'], $result['openid']);
            $this->wxjson=json_encode($userinfo);
            
            if (! $result)
            {
                $current_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                $current_url = str_replace('code=', 'code0=', $current_url);
                redirect($this->wechatObj->getOauthRedirect($current_url, 1, 'snsapi_base'));
                exit();
            }
            $userRes = $this->checkOpenId($result['openid']);
            
            if($userRes['status']==1)
            {
                R('Public/errTip', array( '该用户被禁用,请联系管理员'));
                exit();
            }
            // 获得用户关注着的信息
            $userinfo2 = $this->wechatObj->getUserInfo($result['openid']);
            //如果用户有关注,就获得关注信息,用户如果没有关注，就获得授权信息
            if ($userinfo2['subscribe'] == 0)
            {
                $userOpenId = $userinfo['openid'];
                $userSex = $userinfo['sex'];
                $userNickName = base_encode($userinfo['nickname']);
                $userLanguage = $userinfo['language'];
                $userCity = $userinfo['city'];
                $userProvince = $userinfo['province'];
                $userCountry = $userinfo['country'];
                $userHeadImgUrl = $userinfo['headimgurl'];
                $userJson=json_encode($userinfo);
                $userSubscribe_time = 0;
                $userSubscribeStatus = 0;
                $userUnionid = $userinfo['unionid'];
                $userGroupid = 0;
            } else
            {
                $userOpenId = $userinfo2['openid'];
                $userSex = $userinfo2['sex'];
                $userNickName = base_encode($userinfo2['nickname']);
                $userLanguage = $userinfo2['language'];
                $userCity = $userinfo2['city'];
                $userProvince = $userinfo2['province'];
                $userCountry = $userinfo2['country'];
                $userHeadImgUrl = $userinfo2['headimgurl'];
                $userSubscribe_time = $userinfo2['subscribe_time'];
                $userSubscribeStatus = $userinfo2['subscribe'];
                $userUnionid = $userinfo2['unionid'];
                $userGroupid = $userinfo2['groupid'];
                $userJson=json_encode($userinfo2);
            }
            $userIp = get_client_ip();
            $createTime = time();
         
            if ($userRes == NULL)
            {
                // 新增
                $addwhere['userOpenId'] = $userOpenId;
                $addwhere['userSex'] = $userSex;
                $addwhere['userNickName'] = $userNickName;
                $addwhere['userLanguage'] = $userLanguage;
                $addwhere['userCity'] = $userCity;
                $addwhere['userProvince'] = $userProvince;
                $addwhere['userCountry'] = $userCountry;
                $addwhere['userHeadImgUrl'] = $userHeadImgUrl;
                $addwhere['userSubscribe_time'] = $userSubscribe_time;
                $addwhere['userUnionid'] = $userUnionid;
                $addwhere['groupid'] = $userGroupid;
                $addwhere['userIp'] = $userIp;
                $addwhere['userFrom']='user';
                $addwhere['status']=0;
                $addwhere['createtime'] = $createTime;
                $addwhere['userJson']=$userJson;
                M('user')->add($addwhere);
                // 返回相应的信息
                if(C('CHANGEWECHAT'))
                {
                    $returnArr['openId'] = $userUnionid;
                }else{
                    $returnArr['openId'] = $userOpenId;
                }
                $returnArr['userHeadImgUrl'] = $userHeadImgUrl;
                $returnArr['userNickName'] = base_decode($userNickName);
                $returnArr['userJson']=$userJson;
                return $returnArr;
            } else
            {
                
                // 更新用户信息
                if (time() - $userRes['createtime'] > 60 * 60 * 24*7)
                {
                    $savewhere['userHeadImage'] = $userHeadImgUrl;
                    $savewhere['userNickName'] = $userNickName;
                    // 信息大约1天,就进行数据的 数据的更新
                    M('user')->where(array(
                            'id' => $userRes['id']
                    ))->save($savewhere);
                    // 返回相应的信息
                    if(C('CHANGEWECHAT'))
                    {
                        $returnArr['openId'] = $userRes['userUnionid'];
                    }else{
                        $returnArr['openId'] = $userOpenId;
                    }
                    $returnArr['userHeadImgUrl'] = $userHeadImgUrl;
                    $returnArr['userNickName'] = base_decode($userNickName);
                    $returnArr['userJson']=$userJson;
                    return $returnArr;
                } else
                {
                    // 返回相应的信息
                    if(C('CHANGEWECHAT'))
                    {
                        $returnArr['openId'] = $userRes['userUnionid'];
                    }else{
                        $returnArr['openId'] = $userOpenId;
                    }
                    $returnArr['userHeadImgUrl'] = $userHeadImgUrl;
                    $returnArr['userNickName'] = base_decode($userNickName);
                    $returnArr['userJson']=$userJson;
                    return $returnArr;
                }
            }
        } else
        {
            $result = $this->getOpenidByBaseOauth(NULL, 'AccessToken');
            $openId = $result['openid'];
           
            $userRes = $this->checkOpenId($openId);
            if($userRes['status']==1)
            {
                R('Public/errTip', array( '该用户被禁用,请联系管理员'));
                exit();
            }
            
            if ($userRes != NULL)
            {
               
                // 判断是否已经超过24小时，如果是重新获取，如果不是就返回信息
                if (time() - $userRes['createtime'] > 60 * 60 * 24*7)
                {
                    $userinfo2 = $this->wechatObj->getUserInfo($result['openid']);
                   
                    if ($userinfo2['subscribe'] == 0)
                    {
                        $userinfo = $this->wechatObj->getOauthUserinfo($result['access_token'], $result['openid']);
                        $savewhere['userHeadImage'] = $userinfo['headimgurl'];
                        $savewhere['userNickName'] = base_encode($userinfo['nickname']);
                        $savewhere['userJson']=json_encode($userinfo2);
                    } else
                    {
                        $savewhere['userLanguage'] = $userinfo2['language'];
                        $savewhere['userCity'] = $userinfo2['city'];
                        $savewhere['userProvince'] = $userinfo2['province'];
                        $savewhere['userCountry'] = $userinfo2['country'];
                        $savewhere['userHeadImgUrl'] = $userinfo2['headimgurl'];
                        $savewhere['userSubscribe_time'] = $userinfo2['subscribe_time'];
                        $savewhere['userSubscribeStatus'] = $userinfo2['subscribe'];
                        //$savewhere['userUnionid'] = $userinfo2['unionid'];
                        $savewhere['groupid'] = $userinfo2['groupid'];
                        $savewhere['userJson']=json_encode($userinfo2);
                    }
                    $savewhere['userIp'] = get_client_ip();
                   
                    // 信息大约1天,就进行数据的 数据的更新
                    M('user')->where(array(
                            'id' => $userRes['id']
                    ))->save($savewhere);
                    // 返回相应的信息
                    if(C('CHANGEWECHAT'))
                    {
                        $returnArr['openId'] = $userRes['userUnionid'];
                    }else{
                        $returnArr['openId'] = $openId;
                    }
                    //$returnArr['openId'] = $openId;
                    $returnArr['userHeadImgUrl'] = $userinfo['headimgurl'];
                    $returnArr['userNickName'] = $userinfo['nickname'];
                    $returnArr['userJson']= $savewhere['userJson'];
                    return $returnArr;
                } else
                {
                    // 返回相应的信息
                    if(C('CHANGEWECHAT'))
                    {
                        $returnArr['openId'] = $userRes['userUnionid'];
                    }else{
                        $returnArr['openId'] = $openId;
                    }
                    //$returnArr['openId'] = $openId;
                    $returnArr['userHeadImgUrl'] = $userRes['userHeadImgUrl'];
                    $returnArr['userNickName'] = base_decode($userRes['userNickName']);
                    $returnArr['userJson']= $userRes['userJson'];
                    return $returnArr;
                }
            } else
            {
                $current_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" . "&isOauth=1";
                $current_url = str_replace('code=', 'code0=', $current_url);
                redirect($this->wechatObj->getOauthRedirect($current_url, 1, 'snsapi_userinfo'));
            }
        }
    }
    public function getShareJsSign($shareurl, $openId){
        $jsapi_ticket = null;
        $options=array(
            'appid'=> C('appid'),
            'appsecret'=>C('appsecret'),
        );
        $appid = C('appid');
        $wechatObj=new Wechat($options);
        $wx_user_tpfauth = M('wechataccount');
        $search['appid']=$appid;
        $userjsApiTicketVO=$wx_user_tpfauth->where($search)->find();
       
        if($userjsApiTicketVO){
            if(time()-$userjsApiTicketVO['expires_in']>7000){
                $jsapitoken=$wechatObj->getAccessToken();
                $jsapiticket=$wechatObj->getJsTicket();
               
                if($jsapiticket){
                    $upStr = array();
                    $upStr['appid']=$appid;
                    $upStr['jsapiaccess_token']=$jsapitoken;
                    $upStr['jsapiticket']=$jsapiticket;
                    $upStr['expires_in']=time();
                    $wx_user_tpfauth->where($search)->save($upStr);
                    $jsapi_ticket=$jsapiticket;
                }else{
                    $jsapi_ticket=$userjsApiTicketVO['jsapiticket'];
                }
    
            }else{
                $jsapi_ticket=$userjsApiTicketVO['jsapiticket'];
            }
        }else {
            // 表示不存在
            $jsapitoken=$wechatObj->getAccessToken();
            $jsapiticket=$wechatObj->getJsTicket();
            
            if($jsapiticket){
                $upStr = array();
                $upStr['appid']=$appid;
                $upStr['jsapiaccess_token']=$jsapitoken;
                $upStr['jsapiticket']=$jsapiticket;
                $upStr['expires_in']=time();
                $upStr['createtime']=time();
                $wx_user_tpfauth->add($upStr);
                $jsapi_ticket=$jsapiticket;
            }
        }
        $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $data = $wechatObj->getJsSign($url, time(), '', $appid, $jsapi_ticket);

        //分享域名
        $data['url'] = $shareurl;
        $returnArr['wxid']=$openId;
        $returnArr['fromWxid']=$_GET['fromWxid'];
        $returnArr['shareArg']=$data;
        return $returnArr;
    }
    
    public function getOauthAccessToken(){
        $this->getWeConfig();
       return  $this->wechatObj->getAccessToken();
    }
    //+------------------------------------第三方平台进行用户的信息读取------------------------+//
    public function getComponentOpenidByBaseOauth($authAppid,$type){
        $code = isset($_GET['code'])?$_GET['code']:'';
        $wxThirdPf = new WechatThirdPf('act');
		if (!$code){
		    $current_url = "$_SERVER[REQUEST_URI]";
		    $scope='snsapi_base';
		    $state=1;
		    $codeURL=$wxThirdPf->webOauthFirstFromWx($authAppid, $current_url, $scope, $state);
		    redirect($codeURL);
		    return;
		}else {
		    $result=$wxThirdPf->webOauthSecondFromWx($authAppid, $code);
		    if(!$result){
		        $current_url = "$_SERVER[REQUEST_URI]";
		        $scope='snsapi_base';
		        $state=1;
		        $codeURL=$wxThirdPf->webOauthFirstFromWx($authAppid, $current_url, $scope, $state);
		        redirect($codeURL);
		        return;
		    }
		    $openId=$result['openid'];
		    // 进行access_token保存
		    $where['code']='accesstoken_'.$authAppid;
		    $sysconfig = M('sysconfig');
		    $sysConfig1 = $sysconfig->where($where)->find();
		    if($sysConfig1==NULL){
		        $where['value']=$result['access_token'];
		        $where['remark']='第三方用户静默的access_token';
		        $where['createTime']=date('Y-m-d H:i:s');
		        $sysconfig->add($where);
		        // 保存用户的
		    }
		}
		return $openId;
    }
    public function getComponentOpenidByUserOauth($authAppid){
        $wxThirdPf = new WechatThirdPf('act');
        // 从数据库中获得用户appid的access_token;
        $where['code']='accesstoken_'.$authAppid;
        $sysconfig = M('sysconfig');
        $sysConfig1 = $sysconfig->where($where)->find();
        if($sysConfig1){
        }else {
            
        }
        
    }
    
}
?>